package cn.com.cfae.iras.doc.analyze.components.integrity;

import cn.com.cfae.iras.doc.analyze.components.BaseComponent;
import cn.com.cfae.iras.doc.analyze.components.beans.ComponentResult;
import cn.com.cfae.iras.doc.analyze.parse.kv.KVText;
import cn.com.cfae.iras.doc.analyze.parse.model.ChapterModel;
import cn.com.cfae.iras.doc.analyze.parse.model.ExtractBizModel;
import cn.com.cfae.iras.doc.analyze.parse.model.ExtractItem;
import cn.com.cfae.iras.doc.analyze.parse.model.PageModel;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;

/**
 * Created by 佟媛媛 on 18/10/23.
 */

@Component("I1008")
@Scope("prototype")
public class I1008 extends BaseComponent {

    private static Logger log = LoggerFactory.getLogger(I1008.class);


    /**
     * @auth 佟媛媛
     * @date 18/10/29 下午7:13
     * @desc TODO 以上的主要板块是否含有“盈利模式”、“上游”、“下游”、“产销区域”、“技术工艺”、“行业地位”。如有多个板块符合条件，需要检查各个板块是否分别含有以上关键词 需求暂放二期实现
    检查募集说明书中对近一年或近一期收入占主营业务收入10%以上，或毛利润占10%以上的主要板块是否含有“盈利模式”、“上游”、“下游”、“产销区域”、“技术工艺”、“行业地位”。如有多个板块符合条件，需要检查各个板块是否分别含有以上关键词
     * 若某个板块满足披露条件，但未披露相关内容，提示“XX板块收入占主营业务收入10%以上，但未披露盈利模式”或“XX板块收入占主营业务收入10%以上，但未披露产销区域”或“XX板块毛利润占总毛利润10%以上，但未披露盈利模式”。
     * "1、从营业收入、毛利润表格中提取每项主营业务收入、毛利润和总计进行计算占比，大于10%的业务到营业情况介绍部分检查是否有披露，不存在缺失提示；
    2、判断文字描述＞=5行；
    3、只获取近一年或近一期，满足一期即需披露；
    4、负值不计算占比；

    是否引用
     */
    @Override
    public List<ComponentResult> handlerM() {
        return common("M-5");
    }

    private List<ComponentResult> common(String catalogId){
        List<ComponentResult> list = null;
        setCatalogId(catalogId);
        int pageNum = getChapterModel(getCatalogId()).getStartPage();
        List<String> zybk = new ArrayList<>();
        Map<String,String> yebkmap = new HashMap<>();
        List<Map> pages = new ArrayList<>();
        String[] tables = new String[]{"YYSR","MLR"};//营业收入表、毛利润表
        try{
            for(String table : tables){
                ExtractBizModel model = getModel(getCatalogId(),table);
                List<Map<String, ExtractItem>> _listjyq = model.getTable2(getJYQ(model.getTables2()));
                List<Map<String, ExtractItem>> _listjyn = model.getTable2(getJYN(model.getTables2()));
                if(!CollectionUtils.isEmpty(_listjyq)){
                    for(Map<String, ExtractItem> map : _listjyq){
                        ExtractItem item = map.get("ZB");//占比
                        ExtractItem bkItem = map.get("YWBK");//业务板块
                        if(item!=null){
                            KVText value = item.getValue();
                            if(value!=null){
                                int bei = value.getText().contains("%")?100:100;//默认单位为%
                                double _value = getDouble(value.getText());
                                if(_value > 0.1*bei && _value-1*bei!=0){
                                    if(bkItem.getKey()!=null && !zybk.contains(bkItem.getKey().getText())){
                                        if(org.apache.commons.lang3.StringUtils.isNotEmpty(bkItem.getKey().getText())) {
                                            String bk = bkItem.getKey().getText().replace("\r","").replace("\n","");
                                            zybk.add(bk);
                                            yebkmap.put(bk,(table.equals("YYSR")?"（营业收入表）":"（毛利润表）")+value.getText());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if(!CollectionUtils.isEmpty(_listjyn)){
                    for(Map<String, ExtractItem> map : _listjyn){
                        ExtractItem item = map.get("ZB");//占比
                        ExtractItem bkItem = map.get("YWBK");//业务板块
                        if(item!=null){
                            KVText value = item.getValue();
                            if(value!=null){
                                int bei = value.getText().contains("%")?100:100;//默认单位为%
                                double _value = getDouble(value.getText());
                                if(_value > 0.1*bei && _value-1*bei!=0){
                                    if(bkItem.getKey()!=null && !zybk.contains(bkItem.getKey().getText())){
                                        if(org.apache.commons.lang3.StringUtils.isNotEmpty(bkItem.getKey().getText())){
                                            String bk = bkItem.getKey().getText().replace("\r","").replace("\n","");
                                            zybk.add(bk);
                                            yebkmap.put(bk,(table.equals("YYSR")?"（营业收入表）":"（毛利润表）")+value.getText());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if(CollectionUtils.isEmpty(_listjyq) || CollectionUtils.isEmpty(_listjyn)){
                    list = new ArrayList<>();
                    List<ComponentResult.TextPosition> textPositionList = new ArrayList<>();
                    String promptMsg = (table.equals("YYSR")?"（营业收入表）":"（毛利润表）")+"未抽取到"+(CollectionUtils.isEmpty(_listjyq)?"近一期":"近一年")+"数据";
                    list.add(getComponentResult(true,"02","检查占主营业务收入或毛利润10%以上板块",pageNum,promptMsg,getRuleTitle(),textPositionList));
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        list = getList(zybk,yebkmap);
        if(CollectionUtils.isEmpty(list)){
            ComponentResult result = getComponentResult(true,"02","检查占主营业务收入或毛利润10%以上板块",pageNum,"未抽取到数据",getRuleTitle(),null);
            list.add(result);
        }
        return list;
    }

    private List<ComponentResult> getList(List<String> zybk,Map yebkmap){
        List<ComponentResult> list = new ArrayList<>();
        for(String bk : zybk){
            String promptMsg = bk+"占比"+yebkmap.get(bk);
            boolean exist = false;
            int pageNum = getChapterModel(getCatalogId()).getStartPage();
            List<ComponentResult.TextPosition> textPositionList = new ArrayList<>();
            try{

                for(int j=0;j<getChapterModel(getCatalogId()).getPageModelList().size();j++){
                    PageModel pageModel = getChapterModel(getCatalogId()).getPageModelList().get(j);
                    if(exist) break;
                    Map page = new HashMap();
                    pageNum = pageModel.getPageNumber();
                    JsonArray jsonTextDataArray = pageModel.getJsonTextData()!=null?pageModel.getJsonTextData().getAsJsonArray():null;
                    if(jsonTextDataArray!=null) {
                        for (JsonElement element : jsonTextDataArray) {
                            if(exist) break;
                            JsonArray data = element.getAsJsonObject() != null ? element.getAsJsonObject().getAsJsonArray("data") : null;//当页文本
                            if (data != null) {
                                for(int i=0;i<data.size();i++){
                                    if(exist) break;
                                    JsonObject current = returnOne(data.get(i).getAsJsonArray());
                                    String content = current.get("text").getAsString();
                                    if(Pattern.matches("\\d{1,2}、"+bk+"[\\S\\s]*",content)){
                                        exist = true;
                                        page.put("pageNum",pageNum);page.put("lineNum",i);
                                        double x = current.get("left").getAsDouble();
                                        double y = current.get("top").getAsDouble();
                                        ComponentResult.TextPosition textPosition = new ComponentResult().new TextPosition();
                                        textPosition.setContent(content);
                                        textPosition.setX(x);
                                        textPosition.setY(y);
                                        textPositionList.add(textPosition);
                                    }
                                }
                            }
                        }
                    }
                    if(exist){
                        if(jsonTextDataArray!=null) {
                            for (JsonElement element : jsonTextDataArray) {
                                JsonArray data = element.getAsJsonObject() != null ? element.getAsJsonObject().getAsJsonArray("data") : null;//当页文本
                                Result result = getTextPositionList(data,page,pageModel,j);
                                List<ComponentResult.TextPosition> _textPositionList = result.getList();
//                                textPositionList.addAll(_textPositionList);
                                boolean boo = result.isBoo();
                                if(!boo && _textPositionList.size()<5){
                                    int lines = _textPositionList.size();
                                    if(j<=getChapterModel(getCatalogId()).getPageModelList().size()-2){//连续判断下一页
                                        PageModel _pageModel = getChapterModel(getCatalogId()).getPageModelList().get(j+1);
                                        JsonArray _jsonTextDataArray = _pageModel.getJsonTextData()!=null?_pageModel.getJsonTextData().getAsJsonArray():null;
                                        if(_jsonTextDataArray!=null){
                                            List<ComponentResult.TextPosition> _list = new ArrayList<>();
                                            for (JsonElement _element : _jsonTextDataArray) {
                                                JsonArray _data = _element.getAsJsonObject() != null ? _element.getAsJsonObject().getAsJsonArray("data") : null;//当页文本
                                                page.put("pageNum",pageNum+1);page.put("lineNum",0);
                                                Result _result = getTextPositionList(_data,page,_pageModel,j);
                                                List<ComponentResult.TextPosition> __textPositionList = _result.getList();
                                                lines += __textPositionList.size();
                                                _list.addAll(__textPositionList);
                                            }
                                            if(lines<5){
                                                promptMsg += "，描述小于5行";
                                                exist = false;
                                            }else{
                                                promptMsg += "，描述大于5行";
//                                                textPositionList.addAll(_list);
                                            }
                                        }
                                    }
                                }else{
                                    if(boo && _textPositionList.size()<5){
                                        promptMsg += "，描述小于5行";
                                    }else if(boo && _textPositionList.size()>=5){
                                        promptMsg += "，描述大于5行";
                                    }
                                }
                            }
                        }
                    }

                }
                if(!exist){
                    promptMsg += "，未找到相关文字描述";
                }
            }catch (Exception e){
                log.error(e.getMessage(),e);
            }
            ComponentResult result = getComponentResult(!exist,exist?"01":"02","主营业务-"+bk,pageNum,promptMsg,getRuleTitle(),textPositionList);
            list.add(result);
        }
        return list;
    }

    private Result getTextPositionList(JsonArray data, Map page, PageModel pageModel, int j){
        Result result = new Result();
        List<ComponentResult.TextPosition> textPositionList = new ArrayList<>();
        if (data != null) {
            List<ComponentResult.TextPosition> _textPositionList = new ArrayList<>();
            for(int i=(int)page.get("lineNum")+1;i<data.size();i++){
                JsonObject current = returnOne(data.get(i).getAsJsonArray());
                String content = current.get("text").getAsString();
                double x = current.get("left").getAsDouble();
                double y = current.get("top").getAsDouble();
                ComponentResult.TextPosition textPosition = new ComponentResult().new TextPosition();
                textPosition.setContent(content);
                textPosition.setX(x);
                textPosition.setY(y);
                _textPositionList.add(textPosition);
                if(Pattern.matches("\\d{1,2}、[\\S\\s]*",content) || Pattern.matches("图表[\\S\\s]*",content)){//到下一章节
                    if(i-(int)page.get("lineNum")>=5){
                        _textPositionList.remove(_textPositionList.size()-1);
                        result.setBoo(true);
                        break;
                    }
                }else if(data.size()-(int)page.get("lineNum")>=5 && i==data.size()-1){//到当前页最后
                    result.setBoo(true);
                    break;
                }else{
                    result.setBoo(false);
                }
            }
            textPositionList.addAll(_textPositionList);
        }
        result.setList(textPositionList);
        return result;
    }

    public class Result{
        private List<ComponentResult.TextPosition> list;
        private boolean boo;

        public List<ComponentResult.TextPosition> getList() {
            return list;
        }

        public void setList(List<ComponentResult.TextPosition> list) {
            this.list = list;
        }

        public boolean isBoo() {
            return boo;
        }

        public void setBoo(boolean boo) {
            this.boo = boo;
        }
    }


    @Override
    public List<ComponentResult> handlerBM() {
        return common("BM-5");
    }

    @Override
    public List<ComponentResult> handlerDM() {
        return common("DM-5");
    }

    @Override
    public List<ComponentResult> handlerBDM() {
        return common("BDM-5");
    }


    private ComponentResult getComponentResult(boolean annotationFlag,String exist,String keyword,int pageNum,String promptMsg,String ruleName,List<ComponentResult.TextPosition> textPositionList){
        ComponentResult result = new ComponentResult();
        result.setAnnotationFlag(annotationFlag);
        result.setCatalogId(getCatalogId());
        result.setChapterId(getChapterId());
        result.setExist(exist);
        result.setKeyword(keyword);
        result.setPageNum(pageNum);
        result.setPromptMessage(promptMsg);
        result.setRegulationId(getRegulationId());
        result.setRuleName(ruleName);
        result.setTextPosition(textPositionList);
        result.setUid(UUID.randomUUID().toString());
        return result;
    }


}
